package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.activity.SplashActivity;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.LoginSuccessBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.PhoneIP;
import com.linjian.togetherbirthday.utils.PhoneUUID;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class LoginFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private EditText etUsername;
    private EditText etPassword;
    private Button btGo;
    private CardView cv;
    //    private FloatingActionButton fab;
    public static final String BUILDING = "Building";
    private Bitmap bitmap;
    private TextView getCodeTv,passLoginTv;
    private MyCountDownTimer myCountDownTimer;
    private SplashActivity splashActivity;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_login;
    }

    @Override
    protected void init(View view) {
        mView = view;
        splashActivity = (SplashActivity) getActivity();
        etUsername = view.findViewById(R.id.et_username);
        etPassword = view.findViewById(R.id.et_password);
        btGo = view.findViewById(R.id.bt_go_login);
        cv = view.findViewById(R.id.cv);
//        fab = view.findViewById(R.id.fab);
        getCodeTv = view.findViewById(R.id.get_code);
        passLoginTv = view.findViewById(R.id.passwrod_login_tv);
        //new倒计时对象,总共的时间,每隔多少秒更新一次时间
        myCountDownTimer = new MyCountDownTimer(60000, 1000);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        setListener();
    }


    private void setListener() {
        getCodeTv.setOnClickListener(this);
        btGo.setOnClickListener(this);
        passLoginTv.setOnClickListener(this);
    }

    public static LoginFragment newInstance() {
        LoginFragment loginFragment = new LoginFragment();
        Bundle bundle = new Bundle();
//        bundle.putInt(Integer.class.getName(), resId);
        loginFragment.setArguments(bundle);
        return loginFragment;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get_code:
                if (TextUtils.isEmpty(etUsername.getText())) {
                    TastyToast.makeText(getActivity(), "未输入手机号", TastyToast.LENGTH_SHORT, TastyToast.INFO).show();
                } else {
                    getLoginCode(1, etUsername.getText().toString());
                    try {
                        myCountDownTimer.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.bt_go_login:
                if (TextUtils.isEmpty(etUsername.getText()) || TextUtils.isEmpty(etPassword.getText())) {
                    TastyToast.makeText(getActivity(), "未输入手机号", TastyToast.LENGTH_SHORT, TastyToast.INFO).show();
                } else {
                    if (passLoginTv.getText().toString().equals("密码登录")){
                        httpLogin(etUsername.getText().toString(), etPassword.getText().toString(), 0);
                    }else if (passLoginTv.getText().toString().equals("验证码登录")){
                        httpLogin(etUsername.getText().toString(), etPassword.getText().toString(), 1);
                    }
                }
                break;
            case R.id.passwrod_login_tv:
                if (passLoginTv.getText().toString().equals("密码登录")){
                    passLoginTv.setText("验证码登录");
                    getCodeTv.setVisibility(View.GONE);
                }else if (passLoginTv.getText().toString().equals("验证码登录")){
                    passLoginTv.setText("密码登录");
                    getCodeTv.setVisibility(View.VISIBLE);
                }
                break;
        }
    }


    //倒计时函数
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getCodeTv.setClickable(false);
            getCodeTv.setText(l / 1000 + "秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getCodeTv.setText("重新获取");
            //设置可点击
            getCodeTv.setClickable(true);
        }
    }

    /**
     * 登录请求
     */
    private void httpLogin(String phone, String password, int loginType) {
        Map<String, Object> map = new HashMap<>();
        map.put("phone", phone);
        if (loginType == 0) {
            map.put("code", password);
        } else if (loginType == 1) {
            map.put("password", password);
        }
        map.put("loginip",PhoneIP.getIP(getActivity()));
        map.put("phoneid",PhoneUUID.getPhoneSign(getActivity()));
        HttpUtils.PutLogin(HttpContant.URL + HttpContant.LoginUrl
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i("LoginFragment",response.header("Set-Cookie").concat("SESSION")+"");
                        EventBus.getDefault().post(new NoticeEvent("Cookie",response.header("Set-Cookie")+""));
                        EventBus.getDefault().post(new NoticeEvent("Login", response.body().string()));
                    }
                });
    }

    /**
     * 登录验证码
     */
    public void getLoginCode(int type, String phone) {

        HttpUtils.doGetCode(HttpContant.URL + HttpContant.LoginCode + "?type=" + type + "&&phone=" + phone
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail", "fail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("getLoginCode", response.body().string()));
                    }
                });
    }

    LoginSuccessBean loginSuccessBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "Login":
                Log.i("LoginSuccess", event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        loginSuccessBean = new Gson().fromJson(event.getData().toString(),LoginSuccessBean.class);
                        if (loginSuccessBean.getData().getIsPwd() == 0){
                            splashActivity.replaceFragment("RegistFragment",etUsername.getText().toString());
                        }else if (loginSuccessBean.getData().getSex() == 0){
                            splashActivity.replaceFragment("ChooseGenderFragment",etUsername.getText().toString());
                        } else {
                            SharedPreferencesUtil.put(getActivity(),"LoginPhone",etUsername.getText().toString());
                            Map<String,Object> map = new HashMap<>();
                            map.put("sex",loginSuccessBean.getData().getSex());
                            map.put("nickname",loginSuccessBean.getData().getNickname());
                            map.put("birthday",loginSuccessBean.getData().getBirthday());
                            map.put("height",loginSuccessBean.getData().getHeight());
                            map.put("headImg",loginSuccessBean.getData().getHeadimg());
                            SharedPreferencesUtil.put(getActivity(),"LoginInfo",new Gson().toJson(map));
//                            splashActivity.startActivity("HomeOneFragment");
                            String account = etUsername.getText().toString();
                            String name = String.valueOf(loginSuccessBean.getData().getNickname());
                            splashActivity.login(account,name);
                        }
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            case "getLoginCode":
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200) {

                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "Cookie":
                if (event.getData().toString().length() > 20){
                    String SESSION = event.getData().toString().split(";")[0].split("=")[1];
                    Log.i("LoginFragment",SESSION);
                    SharedPreferencesUtil.put(getActivity(),"Cookie",SESSION);
                }

                break;
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
